<script lang="ts">
  export default {
    name: 'Cart',
  };
</script>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import {
    showConfirmDialog,
    showToast,
    showLoadingToast,
    closeToast,

  } from 'vant';
  import { useRouter, useRoute } from 'vue-router';
  import { useShopNav } from '@/store/modules/app';
  import { useI18n } from 'vue-i18n';
  import API_HOME from '@/apis/home';
  const { t } = useI18n();
  const props = defineProps({
    isCheckout: { type: Boolean, default: true },

  });
  const router = useRouter();
  const route = useRoute();
  const appStore = useShopNav();
  // 购物车数据

  const loading = ref(false);
  // 定义组件事件
  const emit = defineEmits(['close-popup']);
  // 全选状态
  const selectAll = computed({
    get () {
      return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
    },
    set (value: boolean) {
      cartItems.value.forEach(item => {
        item.selected = value;
      });
    }
  });

  // 计算总价
  const totalAmount = computed(() => {
    let total = 0;
    cartItems.value.forEach(item => {
      if (item.selected) {
        const price = parseFloat(item.snapshot_price);

        total += price * item.goods_num;
      }
    });
    return '$' + total.toFixed(2);
  });

  // 选中商品数量
  const selectedCount = computed(() => {
    return cartItems.value.filter(item => item.selected).reduce((total, item) => total + item.goods_num, 0);
  });

  // 移除商品
  const removeItem = async (index: number) => {
    let res = await API_HOME.cartDelete({ ids: index })
    if (res.code == 1) {
      showToast(t('cart.RemovedFromCart'));
      // 更新列表
      appStore.getCarList()
    }
  };

  // 清空购物车
  const clearCart = () => {
    showConfirmDialog({
      title: t('cart.ConfirmToClear'),
      message: t('cart.AreYouSureClearYourCart') + '?',
    }).then(() => {
      cartItems.value = [];
      showToast(t('cart.CartCleared'));
    });
  };

  // 更新数量
  const updateQuantity = async (index: number, goods_num: number, item) => {
    let { goods_id, goods_sku_price_id } = item
    let res = await API_HOME.cartUpdate({
      goods_id,
      goods_num,
      goods_sku_price_id,
      type: 'cover'
    })
  };


  // 结算
  const checkout = () => {
    if (selectedCount.value === 0) {
      showToast(t('cart.PleaseSelectItemsCheckout'));
      return;
    }
    loading.value = true;
    // 模拟结算过程
    setTimeout(() => {
      router.push('/cart');
      loading.value = false;
    }, 1500);
  };

  // 去购物
  const goShopping = () => {
    // 关闭父级弹窗
    emit('close-popup')
    setTimeout(() => {
      router.push('/home');
    }, 500);
  };
  const cartItems = computed(() => appStore.getGoodsChecklist)
  onMounted(() => {
    appStore.getCarCheckList()
    setTimeout(() => {
      if (cartItems.value.length == 0) {
        router.go(-1)
      }
    }, 1000);
  });

</script>

<template>
  <div class="cart-page">
    <div class="cart-title" v-if="isCheckout">
      {{t('cart.ShoppingCart')}}
    </div>
    <div class="cart-container" :style="{ paddingTop: cartItems.length > 0 ? '46px' : '0',}">
      <div class="cart-content">
        <!-- 商品列表 -->
        <template v-if="cartItems.length > 0">
          <van-swipe-cell v-for="(item, index) in cartItems" :key="item.id">
            <div class="cart-item">

              <div class="item-image">
                <img :src="item.goods.image">
              </div>
              <div class="item-info">
                <div>
                  <div class="item-title">{{ item.lang_goods.title }}</div>
                  <div class="item-spec">
                    <span style="margin-right: 6px;" v-for="(size,index) in item.lang_current_sku_price.goods_sku_text"
                      :key="index">{{size.parent_name}}:
                      {{ size.name }} </span>
                  </div>
                  <div class="item-price">${{ item.goods_amount }}</div>
                </div>
                <div class="item-actions">
                  <div class="delete-btn" @click="removeItem(item.id)" v-if="false">
                    <van-icon name="delete" />
                    <span>{{t('home.delete')}}</span>
                  </div>
                  <van-stepper v-model="item.goods_num" theme="round" button-size="22" disabled
                    @change="updateQuantity(index, item.goods_num,item)" />
                </div>
              </div>
            </div>
            <template #right>
              <van-button square type="danger" text="删除" class="delete-btn-large" @click="removeItem(item.id)" />
            </template>
          </van-swipe-cell>
        </template>

        <!-- 空购物车状态 -->
        <div class="empty-cart" v-else>
          <van-icon name="shopping-cart-o" class="empty-cart-icon" />
          <div class="empty-cart-text">{{t('cart.YourShoppingCartIsEmpty')}}</div>
          <van-button type="primary" round size="large" @click="goShopping" v-if="route.path!=='/home'">
            {{t('cart.GoShopping')}}
          </van-button>
        </div>
      </div>
    </div>
    <!-- 下单总计 -->
    <!-- <div class="Payment" v-if="!isCheckout">
      <i>{{t('cart.Total')}}:</i> <i>{{ totalAmount }}</i>
    </div> -->
    <!-- 结算栏 -->
    <div class="checkout-bar" v-if="isCheckout && cartItems.length > 0 ">
      <div class="total-info">
        <van-checkbox v-model="selectAll">{{t('cart.SelectAll')}}</van-checkbox>
        <div class="total-price"> {{t('cart.Total')}}: {{ totalAmount }}</div>
      </div>
      <van-button color="#171717" round @click="checkout">
        {{t('cart.Checkout')}} ({{ selectedCount }})
      </van-button>
    </div>
    <!-- 加载动画 -->
    <div class="loading-overlay" v-if="loading">
      <div class="loading-spinner"></div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  @import './index.less';
</style>